package fragments;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseFragment;
import com.example.administrator.newxlmedical.InventoryActivity;
import com.example.administrator.newxlmedical.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import adapters.VersionAdapter;
import beans.OperateGoodsDetailsBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import constants.Constants;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import netframe.NetReconnectFunc1;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import utils.FormateUtils;
import utils.InventorySortUtils;
import utils.SharedPreferenceUtil;
import utils.ToastUtil;

/**
 * A simple {@link Fragment} subclass.
 */

public class VersionFragment extends BaseFragment {
    @BindView(R.id.tv_version_content)
    TextView tv;
    @BindView(R.id.lv_version_apks)
    ListView listview;

    Unbinder unbinder;
    @BindView(R.id.tv_version_update)
    TextView tvUpdate;
    @BindView(R.id.tv_version_date)
    TextView tvVersionDate;
    private StringBuilder sb = new StringBuilder();
    private List<String> list = new ArrayList<>();
    private SharedPreferences sharedPreferences;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_version, null);
        unbinder = ButterKnife.bind(this, view);
        sharedPreferences = SharedPreferenceUtil.getSharedPreferences(mContext);
        VersionAdapter adapter = new VersionAdapter(mContext, list);
        tvVersionDate.setText("版本更新内容 : 2019-01-09");
        listview.setAdapter(adapter);
        sb.delete(0, sb.length());
        // 获取两个安卓板 对应的U盘路径
        try {
            if (Constants.IS_FUYI) {
                sb.append("/mnt");
                getUsbPath2Fuyi();
            } else {
                sb.append("/mnt/usb_storage");
                getUsbPath2Xiehe();
            }
            Log.e("TTT", "onCreate: " + sb.toString());

        } catch (Exception e) {
            e.printStackTrace();

            tv.setText("获取U盘路径失败");
        }

        File file = new File(sb.toString());
        tv.setText("正在获取U盘中的APK");

        // 获取U盘下所有的apk名称，然后显示
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                int count = 0;
                list.clear();
                for (File f : files) {
                    Log.e(TAG, "file: " + f.getName());
                    if (f.getName().endsWith(".apk")) {
                        count++;
                        list.add(f.getName());
                    }
                }

                if (count != 0) {
                    tv.setText("获取 " + count + " 个APK，请选择安装");
                    for (String s : list) {
                        Log.e(TAG, "onCreateView: " + s);
                    }
                } else {
                    tv.setText("没有找到APK文件!");
                }

            } else {
                tv.setText("U盘路径下的文件夹是空的!");
            }

        } else {
            tv.setText("获取U盘中APK失败!");
        }

        adapter.notifyDataSetChanged();


        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final String apkName = list.get(position);

                AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
                dialog.setTitle("提示");
                dialog.setMessage("确认安装 " + apkName + " 安装包?");

                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

                dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        tv.setText("正在下载,下载完成后会自动安装");

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {

                                    int sum = 0;
                                    int read = 0;

                                    File file = new File(sb.toString() + "/" + apkName);
                                    long length = file.length();

                                    if (file.exists()) {
                                        String uPanApkName = sb.toString() + "/" + apkName;
                                        String installApkName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + apkName;

                                        FileInputStream source = new FileInputStream(uPanApkName);

                                        FileOutputStream fs = new FileOutputStream(installApkName);

                                        byte[] bytes = new byte[2048];

                                        while ((read = source.read(bytes)) != -1) {
                                            sum += read;
                                            fs.write(bytes, 0, read);
                                            float l = sum / ((float) length * 100);
                                            Log.e(TAG, "run: " + sum);
                                        }

                                        // 复制到本地后，安装
                                        installApk(apkName);

                                        source.close();
                                        fs.close();
// 2018-9-19.log
                                    } else {
                                        tv.setText("文件不存在!");
                                    }

                                } catch (Exception e) {

                                    tv.setText("复制文件出错!");

                                }
                            }
                        }).start();

                    }
                });

                dialog.show();

            }
        });

        tvUpdate.setText(
                "1.解决密码登录时的未归数量，与指纹虹膜登录时不一样\r\n" +
                        "2.开关门添加异常记录\r\n" +
                        "3.验收时，记录单片机上传的减量，和异常状态物资的RFID与状态\r\n" +
                        "4.解决盘点的异常都显示在2号柜\r\n" +
                        "5.基数设置，套餐设置默认物品排序\r\n" +
                        "6.解决“用户管理” 页面搜索框弹出的键盘会把标题挤没\r\n" +
                        "7.新增 键盘弹出时，点击空白屏幕会将键盘隐藏\r\n" +
                        "8.添加 预警设置默认物品名排序\r\n" +
                        "9.新增 开关门之后会弹出弹框，可选择继续开门或者退出登录"
        );

//          解决密码登录时的未归数量，与指纹虹膜登录时不一样
//          开关门添加异常记录
//          验收时，记录单片机上传的减量，和异常状态物资的RFID与状态
//          解决盘点的异常都显示在2号柜
//          物品搜索添加 RFID_CODE 字段

        String s = "3000E200379140A3F2C9C103AD9B3000E280681000000039D983F8B03000E200379140A3AE89C103AC8A3000E28068100000003C4CAFA3E33000E200379140A3EC89C103AD823000E28068100000003C4CAE5E863000E28068100000003C4CAE204C     and       ";
        String[] split = s.split(Constants.INCREASE_DECREASE_SPLIT);
//
//        getGoodsDetails1(FormateUtils.getRfidCodes(split[0]),"","3");

        return view;
    }

    private void installApk(String fileName) {
        // 存储apk名称， 启动时删除安装包
        Log.e(TAG, "installApk: " + fileName);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(Constants.APK_NAME, fileName);
        edit.commit();

        File apkFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + fileName);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        startActivity(intent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    private void getUsbPath2Xiehe() {
        File os = new File(sb.toString());
        if (os.exists()) {
            File[] files = os.listFiles();
            int count = 0;
            for (File file : files) {
                Log.e("TTT", "onCreate: " + file.getName() + "    " + file.listFiles().length);
                File[] f = file.listFiles();
                if (f.length > 0) {
                    count++;
                    sb.append("/" + file.getName());
                    File subFile = f[0];
                    sb.append("/" + subFile.getName());
                }
            }
            if (count != 0) {
                tv.setText("已获取U盘路径");
            } else {
                tv.setText("获取U盘路径失败");
            }
        }
    }

    private void getUsbPath2Fuyi() {
        File os = new File(sb.toString());
        if (os.exists()) {
            File[] files = os.listFiles();
            int count = 0;
            for (File file : files) {
                if (file != null && file.getName().startsWith("usbhost")) {
                    File[] f = file.listFiles();
                    if (f != null && file.listFiles().length > 0) {
                        count++;
                        sb.append("/" + file.getName());
                        break;
                    }
                }
            }
            if (count != 0) {
                tv.setText("已获取U盘路径");
            } else {
                tv.setText("获取U盘路径失败");
            }
        }
    }

    private void getGoodsDetails(final ArrayList<String> rfidList, final String cabinetCode, final String type) {
        GetRetrofit.getInstance().getGoodDetails(NetAddress.token, NetAddress.machineCode, rfidList, "", cabinetCode, type)
                .subscribeOn(Schedulers.io())
                .retryWhen(new NetReconnectFunc1())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<OperateGoodsDetailsBean>() {
            @Override
            public void call(OperateGoodsDetailsBean goodsDetailsBean) {


            }
        }, new MyAction1() {
            @Override
            public void call(Throwable throwable) {
                super.call(throwable);
                hideLoadingView();
            }
        });

    }

    private void getGoodsDetails1(final ArrayList<String> rfidList, final String cabinetCode, final String type) {
        GetRetrofit.getInstance().getGoodDetailsInventory(NetAddress.token, NetAddress.machineCode, rfidList, "", cabinetCode, type,"70",NetAddress.deptCode)
                .subscribeOn(Schedulers.io())
                .retryWhen(new NetReconnectFunc1())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<OperateGoodsDetailsBean>() {
            @Override
            public void call(OperateGoodsDetailsBean goodsDetailsBean) {


            }
        }, new MyAction1() {
            @Override
            public void call(Throwable throwable) {
                super.call(throwable);
            }
        });

    }
}
